﻿/************************************************************************
* Copyright (c) 2018 All Rights Reserved.
*命名空间：Wx.Sdk.Api.Src
*文件名： Auth
*创建人： kingling
*创建时间：2018/10/1 14:08:31
*描述
*=======================================================================
*修改标记
*修改时间：2018/10/1 14:08:31
*修改人：kingling
*描述：
************************************************************************/

using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using Wx.Sdk.Api.Entity;
using Wx.Sdk.Api.Entity.Template;
using Wx.Sdk.Utils;
namespace Wx.Sdk.Api.Src
{
    internal class ApiService : IApiService
    {
        WxApi wxApi;
        HttpContext context;
        internal ApiService(WxApi wxApi)
        {
            this.wxApi = wxApi;
            this.context = wxApi.httpContextAccessor.HttpContext;
        }
        void IApiService.Auth(string url, string state, bool agree)
        {
            var scope = agree ? "snsapi_userinfo" : "snsapi_base";
            var link = $"https://open.weixin.qq.com/connect/oauth2/authorize?appid={wxApi.apiOption.appid}&redirect_uri={url}&response_type=code&scope={scope}&state={state}#wechat_redirect";
            context.Response.Redirect(link);
        }

        JsSdk IApiService.GetJsSdkConfig(string url)
        {
            var jsapi_ticket = wxApi.apiBase.getJsApi_Ticket();
            var timestamp = TimeHelper.ToUnix();
            var noncestr = StringHelper.GetRandomString(16);
            var signature = EncyptHelper.ToSha1(string.Format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}", jsapi_ticket, noncestr, timestamp, url)).ToLower();
            var jsapi = new JsSdk()
            {
                appId = wxApi.apiOption.appid,
                nonceStr = noncestr,
                signature = signature,
                timestamp = timestamp
            };
            return jsapi;
        }

        async Task<string> IApiService.GetOpenidWithAuth(string code)
        {
            var url = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={wxApi.apiOption.appid}&secret={wxApi.apiOption.appsecret}&code={code}&grant_type=authorization_code";
            //获取authAccesstoken
            var str = await wxApi.apiBase.Get(url);
            var authAccesstoken = JsonHelper.ToModel<AuthAccessToken>(str);
            return authAccesstoken == null ? "" : authAccesstoken.openid;
        }

        async Task<string> IApiService.GetQRcodeImgSrc(int scene_id, int expire_seconds)
        {
            var postData = expire_seconds == 0 ? "{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": 123}}}" :
                "{\"expire_seconds\": 604800, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": 123}}}";
            return await GetQRcodeImgSrc(postData);
        }

        async Task<string> IApiService.GetQRcodeImgSrc(string scene_str, int expire_seconds)
        {
            var postData = string.Empty;
            postData = expire_seconds == 0 ? "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"123\"}}}" :
                "{\"expire_seconds\": 604800, \"action_name\": \"QR_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"123\"}}}";
            postData = postData.Replace("123", scene_str).Replace("604800", expire_seconds.ToString());
            return await GetQRcodeImgSrc(postData);
        }
        /// <summary>
        /// 获取二维码地址
        /// </summary>
        /// <param name="body"></param>
        /// <returns></returns>
        private async Task<string> GetQRcodeImgSrc(string body)
        {
            var access_token = await wxApi.apiBase.GetAccessToken();
            var url = $"https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={access_token}";
            string str = await wxApi.apiBase.Post(body, url);
            QRcodeTicket qt = JsonHelper.ToModel<QRcodeTicket>(str);
            var realurl = $"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={qt.ticket}";
            return realurl;
        }
        async Task<WxUser> IApiService.GetUserWithAuth(string code)
        {
            var url = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={wxApi.apiOption.appid}&secret={wxApi.apiOption.appsecret}&code={code}&grant_type=authorization_code";
            //获取authAccesstoken
            var str = await wxApi.apiBase.Get(url);
            var authAccesstoken = JsonHelper.ToModel<AuthAccessToken>(str);
            if (authAccesstoken != null)
            {
                //获取用户信息
                var urlforuser = $"https://api.weixin.qq.com/sns/userinfo?access_token={authAccesstoken.access_token}&openid={authAccesstoken.openid}&lang=zh_CN";
                var data = await wxApi.apiBase.Get(urlforuser);
                var user = JsonHelper.ToModel<WxUser>(data);
                return user;
            }
            return null;
        }

        async Task<bool> IApiService.SendTemplateMsg(string touser, string template_id, Keyword first, Keyword remark, string url, Miniprogram miniprogram, params Keyword[] keywords)
        {
            var access_token = await wxApi.apiBase.GetAccessToken();
            var apiUrl = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}";
            var msg = new TemplateMsg(touser, template_id, first, remark, url, miniprogram, keywords);
            var body = JsonHelper.ToJson(msg).Replace("\"{", "{").Replace("}\"", "}").Replace(@"\", "");

            string str = await wxApi.apiBase.Post(body, apiUrl);
            return true;
        }
    }
}
